package main

import (
	"fmt"
	"net"
	"strings"
)

type User struct {
	Name string
	Addr string
	C    chan string
	conn net.Conn

	server *Server
}

func NewUser(conn net.Conn, server *Server) *User {
	//获取ip+端口
	userAddr := conn.RemoteAddr().String()
	user := &User{
		Name:   userAddr,
		Addr:   userAddr,
		C:      make(chan string),
		conn:   conn,
		server: server,
	}

	//创建协程,监视信道
	go user.ListenMessage()
	return user
}

// 一旦信道有消息,就发给对应的客户端
func (this *User) ListenMessage() {
	for {
		msg := <-this.C
		this.conn.Write([]byte(msg + "\n"))
	}
}

func (this *User) Online() {
	//加锁,写入
	this.server.mapLock.Lock()
	this.server.OnlineMap[this.Name] = this
	this.server.mapLock.Unlock()

	fmt.Println(this.Name, "上线了")
	//广播消息
	this.server.BoardCast(this, "上线了")

}

func (this *User) Offline() {
	//加锁,写入
	this.server.mapLock.Lock()
	delete(this.server.OnlineMap, this.Name)
	this.server.mapLock.Unlock()

	fmt.Println(this.Name, "下线了")
	//广播消息
	this.server.BoardCast(this, "下线了")
}

func (this *User) SendMsg(msg string) {
	this.conn.Write([]byte(msg))
}

func (this *User) OnMessage(msg string) {
	if msg == "who" {
		this.server.mapLock.RLock()
		//获取当前的在线列表
		for _, user := range this.server.OnlineMap {
			onlineMsg := "[" + user.Addr + "]" + user.Name + " :" + " 在线...\n"
			this.SendMsg(onlineMsg)
		}
		this.server.mapLock.RUnlock()

	} else if len(msg) > 7 && msg[:7] == "rename|" {
		newName := msg[7:]

		_, ok := this.server.OnlineMap[newName]
		if ok {
			this.SendMsg("输入的名称重复了,换一个试试吧!")
		} else {
			this.server.mapLock.Lock()
			delete(this.server.OnlineMap, this.Name)
			this.server.OnlineMap[newName] = this
			this.server.mapLock.Unlock()
			this.Name = newName
			this.SendMsg("你的名称已经修改为:" + newName + "\n")
		}

	} else if len(msg) > 3 && msg[:3] == "to|" {
		remoteName := strings.Split(msg, "|")[1]
		if remoteName == "" {
			this.SendMsg("格式不正确:to|xxx\n")
			return
		}
		//根据名称查找用户
		remote, ok := this.server.OnlineMap[remoteName]
		if !ok {
			this.SendMsg("当前用户可能下线了,换个用户试试...\n")
			return
		}

		content := strings.Split(msg, "|")[2]
		if content == "" {
			this.SendMsg("消息内容有误,请重试...\n")
			return
		}
		remote.SendMsg(this.Name + "对您说:" + content + "\n")
	} else {
		this.server.BoardCast(this, msg)
	}
}
